<template>
    <div>
        <!-- 查询表单 -->
        <div>
            查询表单
            <el-select size="mini" clearable placeholder="收藏分辨率">
                <el-option label="4K" value="4K"></el-option>
                <el-option label="1080p" value="1080p"></el-option>
                <el-option label="720p" value="720p"></el-option>
                <el-option label="480p" value="480p"></el-option>
                <el-option label="360p" value="360p"></el-option>
                <el-option label="240p" value="240p"></el-option>
                <el-option label="蓝光" value="蓝光"></el-option>
                <el-option label="原盘" value="原盘"></el-option>
                <el-option label="高清" value="高清"></el-option>
                <el-option label="标清" value="标清"></el-option>
                <el-option label="超清" value="超清"></el-option>
                <el-option label="HD" value="HD"></el-option>
                <el-option label="BD" value="BD"></el-option>
                <el-option label="HUD" value="HUD"></el-option>
                <el-option label="TrueHD" value="TrueHD"></el-option>
            </el-select>
            <el-select size="mini" clearable placeholder="收藏清晰度后缀">
                <el-option label="高码率" value="高码率"></el-option>
                <el-option label="120hz" value="120hz"></el-option>
                <el-option label="HDR" value="HDR"></el-option>
                <el-option label="杜比" value="杜比"></el-option>
                <el-option label="IMAX" value="IMAX"></el-option>
            </el-select>
            <el-button :loading="loading" size="small" type="primary" @click="onsubmit()"
                icon="el-icon-search">查询</el-button>
            <el-button icon="el-icon-refresh-right" :loading="loading" size="small" @click="reset()">重置</el-button>
        </div>

        <!-- 工具栏 -->
        <div class="tab-bar fixed-bar">
            <div>
                观影数量:<span style="font-weight: 600">{{ movieList.length }}</span>
            </div>
            <div style="margin-left: 10px">观影总次数:{{ sumWatch() }}</div>
            <el-switch style="margin-left: auto; margin-right: 10px" v-model="CalendarOrCard" active-text="日历"
                inactive-text="卡片">
            </el-switch>
            <el-radio-group size="small">
                <el-radio-button label="观影记录"></el-radio-button>
                <el-radio-button label="待观看"></el-radio-button>
                <el-radio-button label="我的收藏"></el-radio-button>
            </el-radio-group>
            <el-button type="text" style="margin-left: 8px" @click="add()">+新增</el-button>
        </div>

        <!-- 卡片模式 -->
        <div v-if="!CalendarOrCard" class="flex_container">
            <movieCard v-for="(item, index) in movieList.slice(
                (currentPage - 1) * pageSize,
                currentPage * pageSize
            )" :key="index" :details="item"></movieCard>
            <div class="empty_card"></div>
            <div class="empty_card"></div>
            <div class="empty_card"></div>
            <div class="empty_card"></div>
            <div class="empty_card"></div>
        </div>

        <!-- 日历模式 -->
        <div v-else class="calendar-wrap">
            <!-- 年份跳转 -->
            <div style="margin-bottom:10px;">
                <el-input-number v-model="calendarYear" :min="2000" :max="2050" size="small" @change="onYearChange"
                    label="年份"></el-input-number>
            </div>
            <el-calendar v-model="calendarDate" :first-day-of-week="1">
                <template slot="dateCell" slot-scope="{ date }">
                    <div class="calendar-cell">
                        <div class="date-number">{{ date.getDate() }}</div>
                        <ul class="movie-list" v-if="recordsByDate(formatDate(date)).length">
                            <li class="movie-item" v-for="(entry, idx) in recordsByDate(formatDate(date))"
                                :key="formatDate(date) + '-' + idx">
                                <el-popover placement="top" width="320" trigger="hover" :visible-arrow="true">
                                    <div class="popover-content">
                                        <div class="movie-title">{{ entry.movie }}</div>
                                        <div class="movie-meta">
                                            <div v-for="(t, i) in getAllRecords(entry.movie)" :key="i">
                                                <el-link type="primary" @click.prevent="goToDate(t.time)">{{
                                                    formatRecordLabel(t) }}</el-link>
                                            </div>
                                        </div>
                                    </div>
                                    <span slot="reference" class="movie-name" @click="openEntry(entry)">
                                        {{ truncate(entry.movie, 18) }} (第{{ entry.watchIndex }}次)
                                    </span>
                                </el-popover>
                            </li>
                        </ul>
                        <div v-else class="no-movie">-</div>
                    </div>
                </template>
            </el-calendar>
        </div>

        <!-- 分页（仅卡片模式） -->
        <el-pagination v-if="!CalendarOrCard" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[25, 50, 75, 100]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="movieList.length"
            style="float: right; margin-top: 15px"></el-pagination>

        <!-- 弹窗：新增/编辑 -->
        <el-dialog title="新增/编辑" :visible.sync="dialogFormVisible" width="60%">
            <dialog_edit :dialog_form_Props_obj="dialog_form_Props_obj" @confirm="eidt_confirm_father"
                @cancel="eidt_cancel_father"></dialog_edit>
        </el-dialog>
    </div>
</template>

<script>

import * as lang from './lang'
import movieCard from './movieCard.vue'
import dialog_edit from './dialog_edit.vue'

export default {
    components: { movieCard, dialog_edit },
    data () {
        return {
            movieList: [],
            config: lang.default,
            currentPage: 1,
            pageSize: 25,
            dialog_form_Props_obj: { movie: '' },
            dialogFormVisible: false,
            CalendarOrCard: false,
            formParams: {},
            loading: false,
            calendarDate: new Date(),
            calendarYear: new Date().getFullYear(),
        }
    },
    created () {
        this.movieList = this.config.movie
    },
    computed: {
        dateRecordMap () {
            const map = {}
            const toKey = this._toDateKey
            this.movieList.forEach(m => {
                (m.total || []).forEach((t, idx) => {
                    const key = toKey(t.time)
                    if (!key) return
                    if (!map[key]) map[key] = []
                    map[key].push(Object.assign({ movie: m.movie, watchIndex: idx + 1 }, t))
                })
            })
            return map
        },
    },
    methods: {
        formatDate (date) {
            const y = date.getFullYear()
            const m = (date.getMonth() + 1).toString().padStart(2, '0')
            const d = date.getDate().toString().padStart(2, '0')
            return `${y}-${m}-${d}`
        },
        _toDateKey (timeStr) {
            if (!timeStr && timeStr !== 0) return null
            let s = String(timeStr).trim()
            s = s.replace(/\//g, '-')
            if (/^\d{10,}$/.test(s)) {
                const ts = Number(s.length === 10 ? s * 1000 : s)
                const d = new Date(ts)
                if (!isNaN(d)) return this.formatDate(d)
            }
            if (/^\d{4}-\d{1,2}-\d{1,2}$/.test(s)) {
                const parts = s.split('-')
                const y = parts[0], m = parts[1].padStart(2, '0'), d = parts[2].padStart(2, '0')
                return `${y}-${m}-${d}`
            }
            if (/^\d{4}-\d{1,2}$/.test(s)) {
                const parts = s.split('-')
                return `${parts[0]}-${parts[1].padStart(2, '0')}-01`
            }
            if (/^\d{4}$/.test(s)) {
                return `${s}-01-01`
            }
            const d = new Date(s)
            if (!isNaN(d)) return this.formatDate(d)
            return null
        },
        recordsByDate (dateKey) {
            return this.dateRecordMap[dateKey] ? this.dateRecordMap[dateKey] : []
        },
        truncate (str, len = 18) {
            if (!str) return ''
            if (str.length <= len) return str
            return str.slice(0, len - 1) + '…'
        },
        eidt_confirm_father () { this.dialogFormVisible = false },
        eidt_cancel_father () { this.dialogFormVisible = false },
        sumWatch () {
            return this.movieList.reduce((sum, m) => sum + (m.total ? m.total.length : 0), 0)
        },
        add () {
            this.dialog_form_Props_obj = { movie: '' }
            this.dialogFormVisible = true
        },
        openEntry (entry) {
            this.dialog_form_Props_obj = { ...entry }
            this.dialogFormVisible = true
        },
        getTableData () {
            this.loading = true
            setTimeout(() => { this.loading = false }, 800)
        },
        onsubmit () { this.currentPage = 1; this.pageSize = 25; this.getTableData() },
        reset () { this.currentPage = 1; this.pageSize = 25; this.formParams = {}; this.getTableData() },
        handleSizeChange (val) { this.pageSize = val; this.getTableData() },
        handleCurrentChange (val) { this.currentPage = val; this.getTableData() },

        // 新增方法
        getAllRecords (movieName) {
            const movie = this.movieList.find(m => m.movie === movieName)
            if (!movie || !movie.total) return []
            return movie.total.map((t, idx) => Object.assign({ watchIndex: idx + 1 }, t, { movie: movieName }))
        },
        formatRecordLabel (entry) {
            return `${entry.movie} (${entry.watchIndex}次) - ${entry.time}`
        },
        goToDate (timeStr) {
            const dateKey = this._toDateKey(timeStr)
            if (!dateKey) return
            const parts = dateKey.split('-')
            this.calendarDate = new Date(parts[0], parts[1] - 1, parts[2])
        },
        onYearChange (val) {
            // 设置日历年份
            const current = this.calendarDate
            this.calendarDate = new Date(val, current.getMonth(), current.getDate())
        },
    },
}
</script>

<style scoped>
.tab-bar {
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 1000;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    display: flex;
    padding: 10px 0;
    justify-content: center;
}

.flex_container {
    background-color: #2f2f2f;
    display: flex;
    justify-content: flex-start;
    flex-direction: row;
    flex-wrap: wrap;
    padding: 8px;
}

.flex_container>div {
    margin: 5px;
    flex: 1;
    min-width: 380px;
}

.empty_card {
    height: 0;
    margin-top: 0;
    margin-right: 18px;
}

.fixed-bar {
    display: flex;
    align-items: center;
    padding: 0 15px;
}

/* 日历 */
.calendar-wrap {
    padding: 12px;
}

.calendar-cell {
    min-height: 90px;
    padding: 6px;
    box-sizing: border-box;
}

.date-number {
    font-size: 12px;
    font-weight: 700;
    color: #333;
}

.movie-list {
    margin: 6px 0 0;
    padding: 0;
    list-style: none;
    max-height: 68px;
    overflow-y: auto;
}

.movie-item {
    margin-bottom: 4px;
    font-size: 12px;
    line-height: 1;
}

.movie-name {
    display: inline-block;
    max-width: 140px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    cursor: pointer;
    color: #409EFF;
}

.no-movie {
    color: #c0c4cc;
    font-size: 12px;
    margin-top: 6px;
}

.popover-content {
    font-size: 13px;
}

.popover-content .movie-title {
    font-weight: 700;
    margin-bottom: 6px;
}

.popover-content .movie-meta div {
    margin-bottom: 4px;
    color: #555;
    font-size: 13px;
}
</style>
